﻿<template>
    <div class="container activity-child" style="width:99%;margin-top:-25px;">
        <!-- 查询条件 -->
        <div class="query-box">
            <el-form :model="queryBox" status-icon ref="queryBox">
                <el-row>
                    <el-col :span="4">
                        <el-form-item label prop="name">
                            <el-input v-model="queryBox.activityCode" placeholder="请输入内容">
                                <template slot="prepend">活动编码</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label prop="name">
                            <el-input v-model="queryBox.activityName" placeholder="请输入内容">
                                <template slot="prepend">活动名称</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="4">
                        <div class="depart-box">
                            <div class="slect-title">分中心名称</div>
                            <el-autocomplete
                                v-model="centerName"
                                :fetch-suggestions="querySearchAsync"
                                placeholder="请输入内容"
                                @select="handleSelect"
                            ></el-autocomplete>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label prop="name">
                            <el-input v-model="queryBox.centerCode" placeholder="请输入内容">
                                <template slot="prepend">分中心编码</template>
                            </el-input>
                        </el-form-item>
                    </el-col> -->
                </el-row>
            </el-form>
            <div class="from-btns">
                <kt-button
                    :label="$t('action.reset')"
                    perms="true"
                    type="primary"
                    @click="reset('queryBox')"
                />
                <kt-button
                    :label="$t('action.search')"
                    perms="true"
                    type="primary"
                    @click="search"
                />
            </div>
        </div>
        <!-- <div style="float:left;margin-left:2%;margin-bottom:20px;">
            <kt-button
                :disabled="!loadingData"
                label="批量导出"
                perms="activityManage:activity:exportExcel"
                @click="exportExcel"
                type="primary"
            />
        </div> -->
        <!--表格内容栏-->
        <div class="btns">
            <Crm-table
                class="table-width"
                ActivityPerson
                width="400"
                :data="pageResult"
                :columns="columns"
                :loading="loading"
                @findPage="findPage"
                @download="download"
                @toSee="toSee"
                @toSee2="toSee2"
                :showBatchDelete="false"
                @onError="onError"
                @onCopy="onCopy"
            ></Crm-table>
        </div>

        <!-- 查看二维码 -->
        <el-dialog
            title="查看二维码"
            width="20%"
            :visible.sync="addFollow"
            :close-on-click-modal="false"
        >
            <img :src="url+'/'+imgURL" alt />
            <p>活动名称：{{popData.activityName}}</p>
            <!-- <p>活动分中心：{{popData.centerName}}</p> -->
            <kt-button
                class="stu-btn"
                label="下载二维码"
                perms="true"
                type="primary"
                size="medium"
                @click="download(popData2)"
            />
        </el-dialog>
        <!-- 查看海报 -->
        <el-dialog
            title="查看海报"
            width="900px"
            :visible.sync="posterShow"
            :close-on-click-modal="false"
        >
        <div class="containerCanvas">
          <div class="share-img" id="sgareImg">
            <img :src="posterUrlAfter" alt ref="splicingImg" crossorigin="Anonymous" />
        </div>
        <div class="creat-img" ref="box">
                <img :src="posterData.posterUrl" crossorigin="Anonymous" alt />
                <div
                    id="qrcode"
                    :class="[posterData.position==1?'qrcode qrcodeLB':posterData.position==2?'qrcode qrcodeRB':posterData.position==3?'qrcode qrcodeCBBig':posterData.position==4?'qrcode qrcodeCBSmall':'']"
                >
                    <img :src="url+'/'+posterData.path" alt crossorigin="Anonymous" />
                </div>
            </div>
        </div>
        <kt-button
                class="poster-btn"
                label="下载海报"
                perms="true"
                type="primary"
                size="medium"
                @click="downloadImg(posterPopData)"
            />
        </el-dialog>
    </div>
</template>
<script>
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import { CodeToText } from "element-china-area-data";
import { baseUrl } from "@/utils/global";
import axios from "axios";
import Cookies from "js-cookie";
import { qrcanvas } from "qrcanvas";
import html2canvas from "html2canvas";
export default {
    name: "Xuecoo",
    components: {
        CrmTable,
        KtButton
    },
    data() {
        return {
            isShowFlag: 0, //0:初始化部门、人员不显示  1:部门显示 2：人员显示
            checkedPeson: 0,
            size: "mini",

            // 查询条件
            student_data_from_options: [
                {
                    label: " ",
                    key: " "
                }
            ],
            centerName: "",
            queryBox: {},
            url: baseUrl,
            addFollow: false, //显示跟进窗口
            width: 200,
            columns: [
                { type: "index", label: "序号", minWidth: 50 },
                { prop: "activityCode", label: "活动编码", minWidth: 90 },
                { prop: "activityName", label: "活动名称", minWidth: 100 },
                { prop: "createDate", label: "创建时间", minWidth: 100 },
                { prop: "childLink", label: "分中心子链接", minWidth: 200 }
            ],
            pageRequest: { pageNum: 1, pageSize: 10 },
            pageResult: {
                content: []
            },
            loading: false, // 加载标识
            loadingData: false,
            imgURL: "",
            popData: {},
            posterPopData:{},
            exportOemUrl: baseUrl + "/activitySublinkManager/batchExport",
            posterShow:false,
            posterData:{},
            posterUrlAfter:''
        };
    },
    watch:{
      posterUrlAfter(val, oldval) {
            this.$refs.box.style.display = "none";
        },
    },
    methods: {
        // 搜索
        search() {
            if (JSON.stringify(this.queryBox) == "{}") {
                this.$message({
                    message: "请输入筛选项！",
                    type: "error"
                });
            } else {
                this.loadingData = true;
                this.loading = true;
                this.pageRequest.pageNum = 1;
                this.findPage(null);
            }
        },
        handleChange(value) {},
        // 获取分页数据
        findPage: function(data) {
            // if (this.loadingData) {
                if (data !== null) {
                    this.loading = true;
                    this.pageRequest = data.pageRequest;
                }
                this.queryBox.pageSize = this.pageRequest.pageSize;
                this.queryBox.pageNum = this.pageRequest.pageNum;
                this.queryBox.isConsultant = 3;
                this.queryBox.systemUserId = Cookies.get("userId");
                this.$api.agent
                    .extensionManagerList(this.queryBox)
                    .then(res => {
                        if (res.result == 2) {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        } else {
                            let content = {
                                content: res.data,
                                totalSize: res.total
                            };
                            this.pageResult = content;
                            this.pageResult.content.forEach(item => {
                                // 转换状态
                                if (item.status == 1) {
                                    item.statusInfo = "已生成子链接";
                                } else {
                                    item.statusInfo = "未生成子链接";
                                }
                            });
                            this.loading = false;
                        }
                    })
                    .then(data != null ? data.callback : "");
            // }
        },

        // 重置
        reset(queryBox) {
            this.$refs.queryBox.resetFields();
            this.pageResult = {};
            this.queryBox = {};
            this.centerName = "";
            this.loadingData = false;
        },

        // 分中心远程搜索
        querySearchAsync(queryString, callback) {
            let restaurants = [{}];
            let results = "";
            this.$api.dropdown.branchcenter().then(res => {
                for (let i of res.branchCenterInfoList) {
                    i.value = i.name; //将想要展示的数据作为value
                }
                restaurants = res.branchCenterInfoList;
                results = queryString
                    ? restaurants.filter(this.createFilter(queryString))
                    : restaurants;
                callback(results);
            });
        },
        createFilter(queryString) {
            return restaurant => {
                return (
                    restaurant.name
                        .toLowerCase()
                        .indexOf(queryString.toLowerCase()) === 0
                );
            };
        },
        handleSelect(item) {
            this.queryBox.centerName = item.name;
            // this.queryBox.centerName=item.name
        },
        download: function(params) {
            this.$api.agent
                .extensionManQueryQCode({ id: params.row.id })
                .then(res => {
                    if (res.msg != "") {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    } else {
                        this.downloadIamge(
                            baseUrl + "/" + res.data.path,
                            params.row.activityName
                        );
                    }
                });
        },
        downloadIamge(imgsrc, name) {
            //下载图片地址和图片名
            var image = new Image();
            // 解决跨域 Canvas 污染问题
            image.setAttribute("crossOrigin", "anonymous");
            image.onload = function() {
                var canvas = document.createElement("canvas");
                canvas.width = image.width;
                canvas.height = image.height;
                var context = canvas.getContext("2d");
                context.drawImage(image, 0, 0, image.width, image.height);
                var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

                var a = document.createElement("a"); // 生成一个a元素
                var event = new MouseEvent("click"); // 创建一个单击事件
                a.download = name || "photo"; // 设置图片名称
                a.href = url; // 将生成的URL设置为a.href属性
                a.dispatchEvent(event); // 触发a的单击事件
            };
            image.src = imgsrc;
        },
        
        toSee: function(params) {
            this.addFollow = true;
            this.popData = params.row;
            this.popData2 = params;
            this.$api.agent
                .extensionManQueryQCode({ id: params.row.id })
                .then(res => {
                    if (res.result == 1) {
                        this.imgURL = res.data.path;
                    }
                });
        },
        toSee2(params){
          let that = this;
          
          this.$router.push({
              path: "/Customerfile/PosterDetail",
              query: {
                id: params.row.id,
                activityName:params.row.activityName
              }
          });
          // that.posterPopData=params.row
          // that.posterShow=true
          // that.$api.agent.posterAndQCodeUrl({id:params.row.id}).then(res=>{
          //   that.posterData=res.data
          //   that.$nextTick(function() {
          //       html2canvas(that.$refs.box, {
          //           scrollY: 0,
          //           x: 300,
          //           y: 200,
          //           allowTaint: true,
          //           useCORS: true
          //       }).then(function(canvas) {
          //           that.posterUrlAfter = URL.createObjectURL(
          //               that.base64ToBlob(canvas.toDataURL())
          //           );
          //           that.imageSize(canvas.toDataURL());
          //           that.hbSize = parseInt(that.imageSize(canvas.toDataURL()));
          //           that.getImgSize(that.imageSize(canvas.toDataURL()));
          //       });
          //   });
          // })
        },
        // 下载海报
        downloadImg(params) {
          var url = this.$refs.splicingImg.src;
          var xmlhttp;
          xmlhttp = new XMLHttpRequest();
          xmlhttp.open("GET", url, true);
          xmlhttp.responseType = "blob"; // 请求返回的数据类型
          xmlhttp.onload = function () {
            if (this.status == 200) {
              var blob = this.response;
              var img = document.createElement("img"); // 预览图片
              img.onload = function (e) {
                window.URL.revokeObjectURL(img.src);
              };
              img.src = window.URL.createObjectURL(blob);
              img.style.display = "none";
              document.body.appendChild(img);
              var a = document.createElement("a"); // 下载图片
              a.href = window.URL.createObjectURL(blob); //图片地址
              a.download = params.activityName; // 图片名字
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
            }
          };
          xmlhttp.send();
        },
        base64ToBlob(code) {
            let parts = code.split(";base64,");
            let contentType = parts[0].split(":")[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;

            let uInt8Array = new Uint8Array(rawLength);

            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], { type: contentType });
        },
        imageSize(base64Str) {
            const indexBase64 = base64Str.indexOf("base64,");
            if (indexBase64 < 0) return -1;
            const str = base64Str.substr(indexBase64 + 6);
            return parseInt(str.length * 0.75).toFixed(2);
        },
        getImgSize() {
            this.$emit("getImgSize", { hbSize: this.hbSize });
        },
        onCopy(params) {
            this.$message({
                message: "复制成功" + params.text,
                type: "success"
            });
        },
        onError(params) {
            this.$message({
                message: "复制失败",
                type: "error"
            });
        },
        // 批量导出
        exportExcel() {
            let params = Object.assign({}, this.queryBox);
            axios({
                method: "get",
                url: this.exportOemUrl,
                params: params
            }).then(res => {
                window.open(res.request.responseURL);
            });
        }
    }
};
</script>
<style >
@import url("../../assets/queryBox.css");
</style>
<style lang='scss' scoped>
.checked-person {
    font-weight: 500;
    display: inline-block;
    text-align: center;
    margin: 3% 0 3% 0;
}
.batchdistribution-pop-tit {
    font-size: 20px;
    font-weight: bold;
    display: inline-block;
    color: #303133;
}
.el-dialog__wrapper .el-form-item__content {
    margin-left: 0;
}
.demo-form-inline {
    width: 90%;
    margin: 0 auto;
    .el-dialog__body .el-input {
        width: 93% !important;
    }
    .el-select {
        width: 100% !important;
    }
    .tit {
        display: inline-block;
        margin-top: 10%;
    }
}
.btn .el-button {
    padding: 9px 5px !important;
}
</style>
<style>
.batchdistribution-pop .el-dialog__header {
    padding: 0 0 0 0 !important;
}
.activity-child .el-dialog__header {
    padding: 20px 0 0 0 !important;
}
.activity-child .el-dialog__body {
    padding: 20px 20px !important;
}
</style>
<style lang='scss'>
.creat-img {
    width: 630px;
    height: 1125px;
    position: relative;
    // top: 125px;
    // left: 340px;
    img {
        width: 100%;
        height: 100%;
        z-index: 3;
    }
    .qrcode {
        position: absolute;
        z-index: 5;
        display: flex;
        align-items: center;
        justify-content: center;
        // border-radius: 10px;
        background: white;
        img {
            width: 100%;
            height: 100%;
        }
    }
    .qrcodeRB,
    .qrcodeLB {
        width: 210px;
        height: 210px;
        bottom: 20px;
    }
    .qrcodeRB {
        right: 20px;
    }
    .qrcodeLB {
        left: 20px;
    }

    .qrcodeCBBig {
        width: 460px;
        height: 460px;
        bottom: 350px;
        left: 50%;
        margin-left: -230px;
    }
    .qrcodeCBSmall {
        width: 210px;
        height: 210px;
        bottom: 200px;
        left: 50%;
        margin-left: -115px;
    }
}
.containerCanvas {
    width: 630px;
    // height: 1125px;
    position: relative;
    top: 0;
    left: 0;
}
.share-img {
    width: 100%;
    height: 100%;
    img {
        width: 100%;
        height: 100%;
    }
}
.poster-btn{
  position: absolute;
    right: 80px;
    top: 70px;
}
</style>

